package com.qf.fanwang.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //接受参数
            String action= req.getParameter("action");
            if(action==null)
                action="show";
            //获取类对象
            Class clazz=this.getClass();
            // 类对象.getDeclaredMethod(方法名,参数类型的类对象...clazz)
            Method method= clazz.getDeclaredMethod(action, HttpServletRequest.class,HttpServletResponse.class );
            Object obj= method.invoke(this, req,resp);//this指的是action指代的那个方法，使用invoke调用方法
            //重定向或转发
            //转发(页面跳转)

            if(obj instanceof String) {
                String oo=(String) obj;
                if(oo.startsWith("redirect")) {
                    resp.sendRedirect(oo.substring(oo.indexOf(":") + 1));
                    return;
                }else if(oo.startsWith("forward")) {
                    req .getRequestDispatcher(oo.substring(oo.indexOf(":")+1)+".jsp").forward(req, resp);
                    return;
                }else {
                    //异步
                    PrintWriter pw=resp.getWriter();
                    //resp.setContentType("text/html;charset=UTF-8");

                    pw.write(oo);
                    pw.flush();
                }
            }
            //req .getRequestDispatcher(obj+".jsp").forward(req, resp);
            //重定向
            //resp.sendRedirect(obj+".jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
